﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;
using System.Reflection;

namespace GFE.SharePoint
{
    public class AssemblyService
    {
        static ComposablePartCatalog CachedAssemblyPartCatalog = default(ComposablePartCatalog);

        public static ComposablePartCatalog AssemblyPartCatalog
        {
            get {
                    if (CachedAssemblyPartCatalog == default(ComposablePartCatalog))
                        CachedAssemblyPartCatalog = CreateCacheCatalog(GetAssemblyCodebases());
                    return CachedAssemblyPartCatalog; 
            }
        }

        static string[] GetAssemblyCodebases()
        {
            var codebases = new List<string>();

            var farm = SPFarm.Local;
            foreach (var solution in farm.Solutions)
            {
                if (solution.ContainsGlobalAssembly)
                {
                    codebases.Add(solution.Name.Replace(".wsp", ""));
                }
            }
            
            return codebases.ToArray();
        }

        static ComposablePartCatalog CreateCacheCatalog(string[] CodebaseArray)
        {
            Debug.WriteLine("Creating Cache start");
            var assemblyCatalogList = new List<AssemblyCatalog>();
            foreach (var codebase in CodebaseArray)
            {
                try
                {
#pragma warning disable
                    assemblyCatalogList.Add(new AssemblyCatalog(Assembly.LoadWithPartialName(codebase)));
#pragma warning restore
                }
                catch {}
            }
            
            Debug.WriteLine("Creating Cache end");
            return new AggregateCatalog(assemblyCatalogList.ToArray());
        }

        //static ComposablePartCatalog LoadCacheCatalog()
        //{
        //    Console.WriteLine("Reading cache:");
        //    File.Copy("CACHE_PATH", "CACHE_SHADOW_PATH", true);
        //    var catalog = ComposablePartCatalogCachingServices.ReadCatalogFromCache("CACHE_SHADOW_PATH");
        //    if (!catalog.IsCacheUpToDate)
        //    {
        //        Console.WriteLine("Updating cache");
        //        ComposablePartCatalogCachingServices.CacheCatalog(catalog, "CACHE_PATH");
        //    }

        //    return (ComposablePartCatalog)catalog;
        //}

    }

}
